package bsi.vn.Lib;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
 
import bsi.vn.Data.CookieData;
import bsi.vn.Data.CustomerData;
import bsi.vn.Data.ErrorDetailData;
import bsi.vn.Data.ErrorListData;
import bsi.vn.Data.ProvinceData;
import bsi.vn.Data.ResultSearchData;
import bsi.vn.FirstApp.ATMSearchActivity;
import bsi.vn.FirstApp.ContractSearchActivity;
import bsi.vn.FirstApp.InformationActivity;
import bsi.vn.FirstApp.R;
import bsi.vn.FirstApp.ReferenceActivity;
import bsi.vn.FirstApp.SettingActivity;
import bsi.vn.FirstApp.TicketFragmentActivity;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;

public class ProcessFunc {
	
	static InputStream is = null;
	
	public ProcessFunc(){
		
	}
	
	public static String getMd5Hash(String input) {
	  try {
		  MessageDigest md = MessageDigest.getInstance("MD5");
		  byte[] messageDigest = md.digest(input.getBytes());
		  BigInteger number = new BigInteger(1, messageDigest);
		  String md5 = number.toString(16);
		 
		  while (md5.length() < 32)
		  md5 = "0" + md5;
		 
		  return md5;
	  } 
	  catch (NoSuchAlgorithmException e) {
		  Log.e("MD5", e.getLocalizedMessage());
		  return null;
	  }
	}

	public static void ShowMessage(Context context, String Header, String Message)
	{
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("Notice");
        alertDialogBuilder
                .setMessage("Login Error!")
                .setCancelable(false)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                            	//finish();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
	}
	
	public static CookieData GetCookie(Context context) {
		CookieData cookie = new CookieData();
		Cursor cursor;
    	DBAdapter dbAdapter = new DBAdapter(context);
		try {
    		dbAdapter.open();
    		cursor = dbAdapter.getCookie();
    		if (cursor != null ) {
    			if  (cursor.moveToFirst()) {
    				do {
    					cookie.setUserId(cursor.getInt(cursor.getColumnIndex(Consts.DBF_USERID)));
    					cookie.setUserType(cursor.getInt(cursor.getColumnIndex(Consts.DBF_USERTYPE)));
    					cookie.setCookie(cursor.getString(cursor.getColumnIndex(Consts.DBF_COOKIE)));
    					cookie.setIpAddress(cursor.getString(cursor.getColumnIndex(Consts.DBF_IPADDRESS)));
    				}while (cursor.moveToNext());
    			} 
    		}
    	}
    	catch(Exception e){
    		Log.e("log_tag : ", e.toString());
    	}
    	finally {
    		dbAdapter.close();
    	}
    	return cookie; 
    }
	
	public static ArrayList<ErrorDetailData> GetErrorDetailById(Context context, int errorid) {
		ArrayList<ErrorDetailData> myErrorData = new ArrayList<ErrorDetailData>();
		ErrorDetailData errordetail = new ErrorDetailData();
		Cursor cursor;
    	DBAdapter dbAdapter = new DBAdapter(context);
		try { 
    		dbAdapter.open();
    		cursor = dbAdapter.getErrorDetailByErrorId(errorid);
    		if (cursor != null ) {
    			if  (cursor.moveToFirst()) {
    				do {
    					errordetail.setErrorDetailId(cursor.getInt(cursor.getColumnIndex(Consts.DBF_ROWID)));
    					errordetail.setErrorCode(cursor.getInt(cursor.getColumnIndex(Consts.DBF_ORDER)));
    					errordetail.setDescription(cursor.getString(cursor.getColumnIndex(Consts.DBF_DESCRIPTION)));
    					myErrorData.add(errordetail);
    				}while (cursor.moveToNext());
    			} 
    		}
    	}
    	catch(Exception e){
    		Log.e("log_tag : ", e.toString());
    	}
    	finally {
    		dbAdapter.close();
    	}
    	return myErrorData; 
    }
	
	public static ArrayList<ProvinceData> GetProvince(Context context) {
		ArrayList<ProvinceData> myProvince = new ArrayList<ProvinceData>();
		ProvinceData province = new ProvinceData();
		Cursor cursor;
    	DBAdapter dbAdapter = new DBAdapter(context);
		try {
			province = new ProvinceData(0, "Choose province...");
			myProvince.add(province);
    		dbAdapter.open();
    		cursor = dbAdapter.getAllProvinceData();
    		if (cursor != null ) {
    			if  (cursor.moveToFirst()) {
    				do {
    					province = new ProvinceData(cursor.getInt(cursor.getColumnIndex(Consts.DBF_ROWID)), 
    												cursor.getString(cursor.getColumnIndex(Consts.DBF_PROVINCE)));
    					myProvince.add(province);
    				}while (cursor.moveToNext());
    			} 
    		}
    	}
    	catch(Exception e){
    		Log.e("log_tag : ", e.toString());
    	}
    	finally {
    		dbAdapter.close();
    	}
    	return myProvince; 
    }
	
	public static ArrayList<CustomerData> GetCustomer(Context context) {
		ArrayList<CustomerData> myCustomer = new ArrayList<CustomerData>();
		CustomerData customer = new CustomerData();
		Cursor cursor;
    	DBAdapter dbAdapter = new DBAdapter(context);
    	try {
			customer = new CustomerData(0, "Choose customer...");
			myCustomer.add(customer);
			dbAdapter.open();
    		cursor = dbAdapter.getAllCustomerData();
    		if (cursor != null ) {
    			if  (cursor.moveToFirst()) {
    				do {
    					customer = new CustomerData(cursor.getInt(cursor.getColumnIndex(Consts.DBF_ROWID)), 
    												cursor.getString(cursor.getColumnIndex(Consts.DBF_CUSTOMER)));
    					myCustomer.add(customer);
    				}while (cursor.moveToNext());
    			} 
    		}
    	}
    	catch(Exception e){
    		Log.e("log_tag : ", e.toString());
    	}
    	finally {
    		dbAdapter.close();
    	}
    	return myCustomer; 
    }
	
	public static ArrayList<ErrorListData> GetErrorList(Context context) {
		ArrayList<ErrorListData> myErrorList = new ArrayList<ErrorListData>();
		ErrorListData errorlist = new ErrorListData();
		Cursor cursor;
    	DBAdapter dbAdapter = new DBAdapter(context);
    	try {
			dbAdapter.open();
    		cursor = dbAdapter.getAllErrorListData();
    		if (cursor != null ) {
    			if  (cursor.moveToFirst()) {
    				do {
    					errorlist = new ErrorListData(cursor.getInt(cursor.getColumnIndex(Consts.DBF_ROWID)), 
    												cursor.getString(cursor.getColumnIndex(Consts.DBF_ERRORCODE)),
    												cursor.getString(cursor.getColumnIndex(Consts.DBF_DESCRIPTION)));
    					myErrorList.add(errorlist);
    				}while (cursor.moveToNext());
    			} 
    		}
    	}
    	catch(Exception e){
    		Log.e("log_tag : ", e.toString());
    	}
    	finally {
    		dbAdapter.close();
    	}
    	return myErrorList; 
    }
	
	public static ArrayList<ResultSearchData> GetResultSearch(Context context) {
		ArrayList<ResultSearchData> myResultSearch = new ArrayList<ResultSearchData>();
		myResultSearch.add(new ResultSearchData(10,"10"));
		myResultSearch.add(new ResultSearchData(20,"20"));
		myResultSearch.add(new ResultSearchData(50,"50"));
		myResultSearch.add(new ResultSearchData(100,"100"));
		myResultSearch.add(new ResultSearchData(500,"500"));
    	return myResultSearch; 
    }
	
	public static Date stringToDate(String aDate,String aFormat) {

	      if(aDate==null) return null;
	      ParsePosition pos = new ParsePosition(0);
	      SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
	      Date stringDate = simpledateformat.parse(aDate, pos);
	      return stringDate;            
	}
	
	public static void ShowSimpleDialog(Context context, String title, String message)
	{
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle(title);
        alertDialogBuilder
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                            	//SettingActivity.this.finish();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
	}

	public static Intent MenuAction(Context context, MenuItem item)
	{
		Intent intent = new Intent();
		int itemId = item.getItemId();
		if (itemId == R.id.menu_ticket)
			intent = new Intent(context, TicketFragmentActivity.class);
		else if (itemId == R.id.menu_ATM) 
			intent = new Intent(context, ATMSearchActivity.class);
		else if (itemId == R.id.menu_contract) 
			intent = new Intent(context, ContractSearchActivity.class);
		else if (itemId == R.id.menu_reference) 
			intent = new Intent(context, ReferenceActivity.class);
		else if (itemId == R.id.menu_setting) 
			intent = new Intent(context, SettingActivity.class);
		else if (itemId == R.id.menu_information) 
			intent = new Intent(context, InformationActivity.class);
		return intent;
	}
	
	public static String VNFormatDate(int year, int month, int day)
	{
		String dateString = "";
		if (day < 10)
			dateString += "0"+day;
		else
			dateString += day;
		dateString += "/";
		if (month <10)
			dateString += "0" + month;
		else
			dateString += month;
		dateString += "/" + year;
		return dateString;
	}
	public static void hideSoftKeyboard(Activity activity) {
	    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
	}
	
	public static void WriteToFile(Context context, String filename, String data) throws FileNotFoundException {
	       
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
         try {
            fos.write(data.getBytes());
            fos.close();
         } catch (IOException e) {
            Log.e("Controller", e.getMessage() + e.getLocalizedMessage() + e.getCause());
        }
    }

    public static String ReadFromFile(Context context, String filename){
        String line=null;
        String res = null;
        try {
            InputStream in = context.openFileInput(filename);
            if (in != null) {
                InputStreamReader input = new InputStreamReader(in);
                BufferedReader buffreader = new BufferedReader(input);
                res = "";   
                while (( line = buffreader.readLine()) != null) {
                    res += line;
                }
                in.close();
            }
        } catch(Exception e){
           Log.e("file", e.getMessage());
        }
        return res;
    }
}
